package edu.fmi.st.epf.types.projectmember.common.handler;

import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.epf.uma.CustomCategory;

import edu.fmi.st.epf.types.projectmember.common.ProjectMemberActivator;
import edu.fmi.st.epf.types.projectmember.common.util.ProjectMemberHelper;
import edu.fmi.st.epf.types.skill.common.util.SkillHelper;
import eu.tanov.epf.pv.service.types.handler.CustomTypeHandler;
import eu.tanov.epf.pv.service.types.service.CustomTypeHandlersService;
import eu.tanov.epf.pv.service.types.util.CustomCategoryCustomTypeReadOnlySettingDelegate;
import eu.tanov.epf.pv.service.types.util.CustomTypeHelper;

public class ProjectMemberCustomTypeHandler implements
		CustomTypeHandler<CustomCategory> {

	private static final String STRUCTURAL_FEATURE_NAME_SKILLS = "skills";
	/**
	 * XXX if used outside - move to ProjectHelper
	 */
	public static final String TYPE_NAME = "Project member";

	private final EClass projectMemberEClass;
	private EReference skills;

	public ProjectMemberCustomTypeHandler() {
		this.projectMemberEClass = CustomTypeHelper.createType(TYPE_NAME);
	}

	/*
	 * based on http://www.ibm.com/developerworks/library/os-eclipse-dynamicemf/
	 */
	public void registerType() {
		final CustomTypeHandler<CustomCategory> skillTypeHandler = getSkillTypeHandler();
		this.skills = CustomTypeHelper
				.createStructuralFeatureList(
						projectMemberEClass,
						STRUCTURAL_FEATURE_NAME_SKILLS,
						skillTypeHandler.getCustomType(),
						new CustomCategoryCustomTypeReadOnlySettingDelegate<CustomCategory>(
								skillTypeHandler));

		projectMemberEClass.getEStructuralFeatures().add(skills);

		CustomTypeHelper.getExtendedUmaPackage().getEClassifiers()
				.add(projectMemberEClass);
	}

	private CustomTypeHandler<CustomCategory> getSkillTypeHandler() {
		final CustomTypeHandlersService service = ProjectMemberActivator
				.getDefault().getService(CustomTypeHandlersService.class);
		final EClass skillType = SkillHelper.getCustomType();

		return service.getHandlerForType(skillType, CustomCategory.class);
	}

	public EObject wrap(EObject object) {
		return CustomTypeHelper.copy(object, projectMemberEClass);
	}

	public boolean matches(EObject object) {
		return ProjectMemberHelper.isProjectMember(object);
	}

	public EClass getCustomType() {
		return projectMemberEClass;
	}

	public Class<CustomCategory> getHolderType() {
		return CustomCategory.class;
	}

	public String[] getCategoryPkgPath() {
		return ProjectMemberHelper.PROJECT_MEMBERS_PATH;
	}

	public boolean isReadyToRegisterType() {
		// depends on Project Iteraation
		return SkillHelper.isRegistered();
	}

}
